Ensure database connection are checked back into the pool by wrapping calls in with_connection blocks

Dominik Sander 9 years ago
parent
commit
e0f14698ba

+ 3 - 1
app/concerns/long_runnable.rb

@@ -71,7 +71,9 @@ module LongRunnable
71 71
           stop!
72 72
         rescue StandardError => e
73 73
           message = "#{id} Exception #{e.message}:\n#{e.backtrace.first(10).join("\n")}"
74
-          agent.error(message)
74
+          AgentRunner.with_connection do
75
+            agent.error(message)
76
+          end
75 77
         end
76 78
       end
77 79
     end

+ 3 - 1
app/models/agents/jabber_agent.rb

@@ -123,7 +123,9 @@ module Agents
123 123
 
124 124
         time, nick, message = normalize_args(event, args)
125 125
 
126
-        agent.create_event(payload: {event: event, time: time, nick: nick, message: message})
126
+        AgentRunner.with_connection do
127
+          agent.create_event(payload: {event: event, time: time, nick: nick, message: message})
128
+        end
127 129
       end
128 130
 
129 131
       def stop

+ 3 - 1
app/models/agents/twitter_stream_agent.rb

@@ -236,7 +236,9 @@ module Agents
236 236
           next unless (filter.downcase.split(SEPARATOR) - status["text"].downcase.split(SEPARATOR)).reject(&:empty?) == [] # Hacky McHackerson
237 237
           @filter_to_agent_map[filter].each do |agent|
238 238
             puts " -> #{agent.name}"
239
-            agent.process_tweet(filter, status)
239
+            AgentRunner.with_connection do
240
+              agent.process_tweet(filter, status)
241
+            end
240 242
           end
241 243
         end
242 244
       end

+ 9 - 1
lib/agent_runner.rb

@@ -57,6 +57,12 @@ class AgentRunner
57 57
     @@agents << agent unless @@agents.include?(agent)
58 58
   end
59 59
 
60
+  def self.with_connection
61
+    ActiveRecord::Base.connection_pool.with_connection do
62
+      yield
63
+    end
64
+  end
65
+
60 66
   private
61 67
   def run_workers
62 68
     workers             = load_workers
@@ -83,7 +89,9 @@ class AgentRunner
83 89
       next if @options[:only] && !@options[:only].include?(klass)
84 90
       next if @options[:except] && @options[:except].include?(klass)
85 91
 
86
-      (klass.setup_worker || []).each do |agent_worker|
92
+      AgentRunner.with_connection do
93
+        (klass.setup_worker || [])
94
+      end.each do |agent_worker|
87 95
         workers[agent_worker.id] = agent_worker
88 96
       end
89 97
     end